package service

import (
	"cooke-home/common/model/base_dto"
	"cooke-home/task-service/mapper"
	"cooke-home/task-service/model/dto"
	"cooke-home/task-service/model/entity"
	"errors"
)

type TaskServiceImpl struct {
	taskMapper mapper.TaskMapper
}

func NewTaskServiceImpl(taskMapper mapper.TaskMapper) *TaskServiceImpl {
	return &TaskServiceImpl{
		taskMapper: taskMapper,
	}
}

func (ts *TaskServiceImpl) Save(taskDto *dto.TaskDto) error {
	return ts.taskMapper.Save(taskDto)
}

func (ts *TaskServiceImpl) Delete(batchDeleteDto base_dto.BatchDeleteDto) error {
	return ts.taskMapper.Delete(batchDeleteDto)
}

func (ts *TaskServiceImpl) Update(taskDto *dto.TaskDto) error {
	return ts.taskMapper.Update(taskDto)
}

func (ts *TaskServiceImpl) Get(id int64) (*entity.TaskEntity, error) {
	return ts.taskMapper.Get(id)
}

func (ts *TaskServiceImpl) GetList(parentId int64) ([]*entity.TaskEntity, error) {
	return ts.taskMapper.GetList(parentId)
}

func (ts *TaskServiceImpl) UpdateCompleteByParentId(taskDto *dto.TaskDto) error {
	tasks, _ := ts.taskMapper.GetList(taskDto.ParentID)
	parentTask, _ := ts.taskMapper.Get(taskDto.ParentID)

	tasks = append(tasks, parentTask)

	for _, task := range tasks {
		// 如果存在商品名
		// 那么就需要单价 和 单位
		if task.CommodityName != "" && (task.Price == 0 || task.Unit == 0) {
			return errors.New("price and unit cannot be nil or zero")
		}
	}

	return ts.taskMapper.UpdateCompleteByParentId(taskDto)
}

func (ts *TaskServiceImpl) GetByComplete(parentId int64, isComplete int) ([]*entity.TaskEntity, error) {
	return ts.taskMapper.GetByComplete(parentId, isComplete)
}
